﻿using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace SwiftCode.BBS.Common.Helper
{
    public class JWTHelper
    {
        public static string IssueJwt(TokenModelJWT tokenModel)
        {
            //string iss = Appsettings.app(new string[] { "Audience", "Issuer" });
            //string aud = Appsettings.app(new string[] { "Audience", "Audience" });
            //string secret = Appsettings.app(new string[] { "Audience", "Secret" });

            string iss = "SwiftCode.BBS";
            string aud = "whx";
            string secret = "JD8SD0ASDjsd23j342n547df78s";
            string[] roles = { "Admin", "User" };
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, tokenModel.Uid.ToString()),
                new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim(JwtRegisteredClaimNames.Exp, $"{new DateTimeOffset(DateTime.Now.AddSeconds(1000)).ToUnixTimeSeconds()}"),
                new Claim(ClaimTypes.Expiration, (DateTime.Now.AddSeconds(1000)).ToString()),
                new Claim(JwtRegisteredClaimNames.Iss, iss),
                new Claim(JwtRegisteredClaimNames.Aud, aud),
            };

            Claim r1 = new Claim(ClaimTypes.Role, roles[0]);
            Claim r2 = new Claim(ClaimTypes.Role, roles[1]);
            claims.Add(r1);
            claims.Add(r2);
            //claims.AddRange(tokenModel.Role.Split(',').Select(s => new Claim(ClaimTypes.Role, s)));
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var jwt = new JwtSecurityToken(
                issuer: iss,
                claims: claims,
                signingCredentials: creds);

            var jwtHandler = new JwtSecurityTokenHandler();
            var encodedJwt = jwtHandler.WriteToken(jwt);

            return encodedJwt;
        }
        // 发放JWT
        //public static string IssueJwt(TokenModelJWT tokenModelJwt)
        //{
        //    // 配置JWT的iss和aud，即发放方和接收方
        //    string iss = "SwiftCode.BBS";
        //    string aud = "whx";
        //    // 密钥，用于签名JWT
        //    string secret = "JD8SD0ASDjsd23j342n547df78s";
        //    // 角色列表
        //    string[] roles = { "Admin", "User" };

        //    // 创建JWT的payload
        //    var claims = new List<Claim>
        //    { 
        //        // 签发时间
        //        new Claim(JwtRegisteredClaimNames.Iat, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
        //        // JWT的唯一标识
        //        new Claim(JwtRegisteredClaimNames.Jti, tokenModelJwt.Uid.ToString()),
        //        // 生效时间
        //        new Claim(JwtRegisteredClaimNames.Nbf, $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
        //        // 过期时间
        //        new Claim(JwtRegisteredClaimNames.Exp,
        //                  $"{new DateTimeOffset(DateTime.Now.AddSeconds(1200)).ToUnixTimeSeconds}"),
        //        // JWT的过期时间，也可以通过Exp设置
        //        //new Claim(ClaimTypes.Expiration,
        //                 // $"{new DateTimeOffset(DateTime.Now.AddSeconds(1200)).ToUnixTimeSeconds}"),
        //        // 发放方
        //        new Claim(JwtRegisteredClaimNames.Iss, iss),
        //        // 接收方
        //        new Claim(JwtRegisteredClaimNames.Aud, aud)
        //    };

        //    // 添加角色信息到payload
        //    Claim r1 = new Claim(ClaimTypes.Role, roles[0]);
        //    Claim r2 = new Claim(ClaimTypes.Role, roles[1]);
        //    claims.Add(r1);
        //    claims.Add(r2);

        //    // 用密钥对JWT进行签名
        //    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret));
        //    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        //    // 创建JWT
        //    var jwt = new JwtSecurityToken(issuer: iss, claims: claims, signingCredentials: creds);

        //    // 将JWT转换为字符串格式
        //    var jwtHandler = new JwtSecurityTokenHandler();
        //    var encodeJwt = jwtHandler.WriteToken(jwt);

        //    // 返回JWT字符串
        //    return encodeJwt;
        //}

        // 解析JWT
        public static TokenModelJWT DeserializeJwt(string jwtStr)
        {
            // 创建JWT解析器
            var jwtHandler = new JwtSecurityTokenHandler();
            TokenModelJWT tokenModelJwt = new TokenModelJWT();

            // 判断JWT字符串是否为空，并且是否能够被解析
            if (!string.IsNullOrEmpty(jwtStr) && jwtHandler.CanReadToken(jwtStr))
            {
                // 解析JWT
                JwtSecurityToken jwtToken = jwtHandler.ReadJwtToken(jwtStr);
                object role;
                jwtToken.Payload.TryGetValue(ClaimTypes.Role, out role);

                tokenModelJwt = new TokenModelJWT
                {
                    Uid = Convert.ToInt64(jwtToken.Id),
                    Role = role == null ? "" : role.ToString()
                };
            }
            return tokenModelJwt;
        }
    }
}
